using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TradeFlow.Server.Dto;
using TradeFlow.Server.Models;
using SqlSugar;
using TradeFlow.Server.Language;

namespace TradeFlow.Server.Service
{
    /// <summary>
    /// 业务单表头服务类
    /// </summary>
    public class JxBillHeadService : IApplicationService
    {
        private readonly SugarRepository<JxBillHead> _repository;
        private readonly SugarRepository<JxBillList> _listRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository"></param>
        /// <param name="listRepository"></param>
        public JxBillHeadService(SugarRepository<JxBillHead> repository, SugarRepository<JxBillList> listRepository )
        {
            _repository = repository;
            _listRepository = listRepository;
        }
        //public Task<PagingResult<BillInfo>> QueryBillsAsync(PagingCriteria criteria)
        //{
        //    return Database.Query<JxBillHead>(criteria).ToPageAsync<BillInfo>();
        //}

        //public async Task<BillInfo> GetBillAsync(string id)
        //{
        //    BillInfo info = null;
        //    await Database.QueryActionAsync(async db =>
        //    {
        //        info = await db.Query<JxBillHead>().Where(d => d.Id == id).FirstAsync<BillInfo>();
        //        if (info == null)
        //        {
        //            var maxNo = await db.GetMaxBillNoAsync(id);
        //            info = new BillInfo
        //            {
        //                Type = id,
        //                BillNo = maxNo,
        //                Status = BizStatus.Save,
        //                BillDate = DateTime.Now
        //            };
        //        }
        //        info.Lists = await db.Query<JxBillList>().Where(d => d.HeadId == id).ToListAsync<BillListInfo>();
        //    });
        //    return info;
        //}

        //public async Task<Result> DeleteBillsAsync(List<BillInfo> infos)
        //{
        //    if (infos == null || infos.Count == 0)
        //        return Result.Error(Language.SelectOneAtLeast);

        //    if (infos.Exists(d => d.Status != BizStatus.Save))
        //        return Result.Error(AppCoreLanguage.TipOperateSaveRecord);

        //    var database = Database;
        //    var oldFiles = new List<string>();
        //    var result = await database.TransactionAsync(Language.Delete, async db =>
        //    {
        //        foreach (var item in infos)
        //        {
        //            await db.DeleteFilesAsync(item.Id, oldFiles);
        //            await db.DeleteFlowAsync(item.Id);
        //            await db.DeleteAsync<JxBillList>(d => d.HeadId == item.Id);
        //            await db.DeleteAsync<JxBillHead>(item.Id);
        //        }
        //    });
        //    if (result.IsValid)
        //        AttachFile.DeleteFiles(oldFiles);
        //    return result;
        //}

        //public async Task<Result> UnVerifyBillsAsync(List<BillInfo> infos)
        //{
        //    if (infos == null || infos.Count == 0)
        //        return Result.Error(Language.SelectOneAtLeast);

        //    return await Database.TransactionAsync("反审", async db =>
        //    {
        //        foreach (var item in infos)
        //        {
        //            var model = await db.QueryByIdAsync<JxBillHead>(item.Id);
        //            if (model != null)
        //            {
        //                model.Status = BizStatus.Save;
        //                await db.SaveAsync(model);
        //                await db.AddFlowLogAsync(model.Id, "取消审核", "反审", "取消单证审核");
        //            }
        //        }
        //    });
        //}

        //public async Task<Result> SaveBillAsync(UploadInfo<BillInfo> info)
        //{
        //    var database = Database;
        //    var model = await database.QueryByIdAsync<JxBillHead>(info.Model.Id);
        //    model ??= new JxBillHead();
        //    model.FillModel(info.Model);

        //    if (model.Status != BizStatus.Save)
        //        return Result.Error(AppCoreLanguage.TipOperateSaveRecord);

        //    var vr = model.Validate(Context);
        //    if (!vr.IsValid)
        //        return vr;

        //    var fileFiles = info.Files?.GetAttachFiles(nameof(BillInfo.Files), "BillFiles");
        //    return await database.TransactionAsync(Language.Save, async db =>
        //    {
        //        if (model.IsNew)
        //        {
        //            model.BillNo = await db.GetMaxBillNoAsync(model.Type);
        //            await db.CreateFlowAsync(BillFlow.GetBizInfo(model));
        //        }
        //        if (info.Model.IsVerify)
        //        {
        //            model.Status = BizStatus.Verified;
        //            await db.AddFlowLogAsync(model.Id, "单证审核", "审核", "单证已审核");
        //        }
        //        await db.AddFilesAsync(fileFiles, model.Id, key => model.Files = key);
        //        await db.SaveAsync(model);
        //        //更新表体数据
        //        await db.DeleteAsync<JxBillList>(d => d.HeadId == model.Id);
        //        if (info.Model.Lists != null && info.Model.Lists.Count > 0)
        //        {
        //            var index = 1;
        //            foreach (var item in info.Model.Lists)
        //            {
        //                var list = new JxBillList();
        //                list.FillModel(item);
        //                list.HeadId = model.Id;
        //                list.SeqNo = index++;
        //                await db.SaveAsync(list);
        //            }
        //        }
        //        info.Model.Id = model.Id;
        //    }, info.Model);
        //}

        /// <summary>
        /// 查询业务单表头分页列表
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<RestfulResult<PageResult<JxBillHead>>> GetPagesAsync(JxBillHeadPageParam param)
        {
            try
            {
                var query = _repository.AsQueryable();
                
                // 根据参数进行条件筛选
                if (!string.IsNullOrEmpty(param.Type))
                {
                    query = query.Where(x => x.Type == param.Type);
                }
                if (!string.IsNullOrEmpty(param.BillNo))
                {
                    query = query.Where(x => x.BillNo.Contains(param.BillNo));
                }
                if (!string.IsNullOrEmpty(param.Status))
                {
                    query = query.Where(x => x.Status == param.Status);
                }
                if (!string.IsNullOrEmpty(param.Partner))
                {
                    query = query.Where(x => x.Partner == param.Partner);
                }
                if (param.StartDate.HasValue)
                {
                    query = query.Where(x => x.BillDate >= param.StartDate);
                }
                if (param.EndDate.HasValue)
                {
                    // 结束日期加一天，包含当天的所有数据
                    query = query.Where(x => x.BillDate < param.EndDate.Value.AddDays(1));
                }

                // 执行分页查询
                var result = await query.OrderBy(x => x.BillDate, OrderByType.Desc)
                    .ToPageAsync(param.CurrentPage, param.PageSize);
                
                return new RestfulResult<PageResult<JxBillHead>>()
                {
                    Data = result,
                    Code = 0,
                    Message = "查询成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<PageResult<JxBillHead>>()
                {
                    Code = 0,
                    Message = "查询失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 获取所有业务单表头列表
        /// </summary>
        /// <returns></returns>
        public async Task<RestfulResult<List<JxBillHead>>> GetListAsync()
        {
            try
            {
                var query = _repository.AsQueryable();
                var list = await query.ToListAsync();
                return new RestfulResult<List<JxBillHead>>()
                {
                    Data = list,
                    Code = 0,
                    Message = "查询成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<List<JxBillHead>>()
                {
                    Code = 0,
                    Message = "查询失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 根据ID获取业务单表头
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<RestfulResult<JxBillHead>> GetByIdAsync(long id)
        {
            try
            {
                var entity = await _repository.AsQueryable().Where(x => x.Id == id).FirstAsync();
                return new RestfulResult<JxBillHead>()
                {
                    Data = entity,
                    Code = 0,
                    Message = "查询成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<JxBillHead>()
                {
                    Code = 0,
                    Message = "查询失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 增加业务单表头
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<RestfulResult<object>> AddAsync(JxBillHead entity)
        {
            try
            {
                // 验证必填字段
                if (string.IsNullOrEmpty(entity.BillNo))
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "单据编号不能为空"
                    };
                }
                if (string.IsNullOrEmpty(entity.Type))
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "单据类型不能为空"
                    };
                }
                if (string.IsNullOrEmpty(entity.Partner))
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "往来单位不能为空"
                    };
                }

                // 设置创建信息
                entity.CreateTime = DateTime.Now;

                // 保存表头数据
                await _repository.InsertAsync(entity);

                return new RestfulResult<object>()
                {
                    Data = true,
                    Code = 0,
                    Message = "添加成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "添加失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 更新业务单表头
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<RestfulResult<object>> UpdateAsync(JxBillHead entity)
        {
            try
            {
                // 检查是否存在
                var oldEntity = await _repository.AsQueryable().Where(x => x.Id == entity.Id).FirstAsync();
                if (oldEntity == null)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "数据不存在"
                    };
                }

                // 已提交/已审核的单据不允许修改
                if (oldEntity.Status == "已提交" || oldEntity.Status == "已审核")
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "已审核的单据不能编辑"
                    };
                }

                // 更新数据，设置修改时间
                entity.ModifyTime = DateTime.Now;
                await _repository.UpdateAsync(entity);

                return new RestfulResult<object>()
                {
                    Data = true,
                    Code = 0,
                    Message = "更新成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "更新失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 删除业务单表头
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<RestfulResult<object>> DeleteAsync(List<long> ids)
        {
            try
            {
                // 检查是否有已提交或已审核的单据
                var count = await _repository.AsQueryable().Where(x => ids.Contains(x.Id) && (x.Status == "已提交" || x.Status == "已审核")).CountAsync();
                if (count > 0)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "已审核的单据不能删除"
                    };
                }

                // 删除关联的表体数据
                var headIdStrings = ids.Select(id => id).ToList();
                await _listRepository.DeleteAsync(x => headIdStrings.Contains(x.HeadId));

                // 删除表头数据
                dynamic[] idArray = ids.Select(id => (dynamic)id).ToArray();
                await _repository.DeleteByIdsAsync(idArray);

                return new RestfulResult<object>()
                {
                    Data = true,
                    Code = 0,
                    Message = "删除成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "删除失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 提交业务单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<RestfulResult<object>> SubmitAsync(long id)
        {
            try
            {
                var entity = await _repository.AsQueryable().Where(x => x.Id == id).FirstAsync();
                if (entity == null)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "数据不存在"
                    };
                }

                if (entity.Status == "已提交")
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "单据已提交"
                    };
                }

                // 检查是否有表体数据
                var listCount = await _listRepository.AsQueryable().Where(x => x.HeadId == id).CountAsync();
                if (listCount == 0)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "单据无表体数据"
                    };
                }

                // 更新状态
                entity.Status = "已审核";
                entity.ModifyTime = DateTime.Now;
                await _repository.UpdateAsync(entity);

                return new RestfulResult<object>()
                {
                    Data = true,
                    Code = 0,
                    Message = "提交成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<object>()
                {
                    Code = 0,
                    Message = "提交失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 复制业务单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [UnitOfWork]
        public async Task<RestfulResult<object>> CopyAsync(long id)
        {
            try
            {
                var oldEntity = await _repository.AsQueryable().Where(x => x.Id == id).FirstAsync();
                if (oldEntity == null)
                {
                    return new RestfulResult<object>()
                    {
                        Code = 0,
                        Message = "数据不存在"
                    };
                }

                // 创建新单据
                var newEntity = new JxBillHead
                {
                    BillNo = GenerateNewBillNo(oldEntity.Type),
                    Type = oldEntity.Type,
                    Status = "暂存",
                    BillDate = DateTime.Now,
                    Partner = oldEntity.Partner,
                    ContractNo = oldEntity.ContractNo,
                    InvoiceNo = oldEntity.InvoiceNo,
                    Logistics = oldEntity.Logistics,
                    LogisticsNo = oldEntity.LogisticsNo,
                    TotalAmount = oldEntity.TotalAmount,
                    SettleMode = oldEntity.SettleMode,
                    ReturnNo = oldEntity.ReturnNo,
                    LogisticsFee = oldEntity.LogisticsFee,
                    CreateTime = DateTime.Now
                };

                // 保存新单据
                await _repository.InsertAsync(newEntity);

                // 复制表体数据
                var oldDetails = await _listRepository.AsQueryable().Where(x => x.HeadId == id).ToListAsync();
                foreach (var detail in oldDetails)
                {
                    var newDetail = new JxBillList
                    {
                        HeadId = newEntity.Id,
                        SeqNo = detail.SeqNo,
                        Code = detail.Code,
                        Name = detail.Name,
                        Category = detail.Category,
                        Model = detail.Model,
                        Producer = detail.Producer,
                        Unit = detail.Unit,
                        Qty = detail.Qty,
                        Price = detail.Price,
                        Amount = detail.Amount,
                        Note = detail.Note
                    };
                    await _listRepository.InsertAsync(newDetail);
                }

                return new RestfulResult<dynamic>()
                {
                    Data = newEntity,
                    Code = 0, // 使用0表示成功，避免CodeStatus类型错误
                    Message = "复制成功"
                };
            }
            catch (Exception ex)
            {
                return new RestfulResult<dynamic>()
                {
                    Code = 0,
                    Message = "复制失败: " + ex.Message
                };
            }
        }

        /// <summary>
        /// 生成新的单据编号
        /// </summary>
        /// <param name="billType"></param>
        /// <returns></returns>
        private string GenerateNewBillNo(string billType)
        {
            // 生成规则：类型前缀 + 年月日 + 4位流水号
            string prefix = "JH";
            if (billType == "销售出货")
            {
                prefix = "XS";
            }
            else if (billType == "采购退货")
            {
                prefix = "TH";
            }
            else if (billType == "销售退货")
            {
                prefix = "XSTH";
            }

            string dateStr = DateTime.Now.ToString("yyyyMMdd");
            string maxNo = _repository.AsQueryable().Where(x => x.BillNo.StartsWith(prefix + dateStr)).Max(x => x.BillNo);
            int sequence = 1;
            if (!string.IsNullOrEmpty(maxNo))
            {
                string seqStr = maxNo.Substring(prefix.Length + dateStr.Length);
                if (int.TryParse(seqStr, out int currentSeq))
                {
                    sequence = currentSeq + 1;
                }
            }

            return $"{prefix}{dateStr}{sequence.ToString("0000")}";
        }
    }
}